package com.chy.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chy.common.BaseContext;
import com.chy.common.R;
import com.chy.common.Utils;
import com.chy.entity.Article;
import com.chy.mapper.ArticleMapper;
import com.chy.service.ArticleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;
    @Override
    public R<String> addArticle(Map<String, Object> params) {
        String s = JSON.toJSONString(params);
        Article article = JSON.parseObject(s, Article.class);
        article.setUserId(BaseContext.getCurrentId() != null ? BaseContext.getCurrentId() : 0);
        return this.save(article) ? R.success() : R.error();
    }

    @Override
    public R<String> updateArticle(Map<String, Object> params) {
        Boolean flag = articleMapper.updateArticle(params);
        return flag ? R.success() : R.error();
    }

    @Override
    public R<String> deleteArticle(List<Map<String, Object>> lists) {
        int ids = articleMapper.deleteBatchIds(lists);
        return ids > 0 ? R.success() : R.error();
    }

    @Override
    public Page selectByPage(Map<String, Object> params) {
        Integer page = (Integer) params.get("page");
        Integer pageSize = (Integer) params.get("pageSize");
        String title = (String) params.get("title");
        Page pageInfo = new Page(page, pageSize);
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(title), "article.title", title)
                .eq("article.deleted", 0)
                .orderByDesc("article.sort")
                .orderByDesc("article.create_time");
//        articleMapper.selectMapsPage(pageInfo, wrapper);
        articleMapper.selectMyPage(pageInfo, wrapper);
        return pageInfo;
    }

    @Override
    public R<Object> getArtById(Map<String, Object> params) {
        String s = JSON.toJSONString(params);
        Article article = JSON.parseObject(s, Article.class);
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.eq("article.art_id", article.getId());
        Object one = articleMapper.getArtById(article.getId());
        return one != null ? R.success(one) : R.error();
    }
}
